package org.casper.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.casper.bean.Board;
import org.casper.service.BoardService;
import org.casper.util.DateUtil;

/**
 * Servlet implementation class BoardServlet
 */
public class BoardServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private BoardService boardService = new BoardService();
	private HttpSession session = null;
	private PrintWriter out = null;

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		session = req.getSession();
		out =resp.getWriter();
		String op = req.getParameter("op");
		if(op.equals("addBoard")){
			addBoard(req,resp);
		}else if(op.equals("adminIndex")){
			adminIndex(req,resp);
		}else if(op.equals("checkBoardNameOnly")){
			checkBoardNameOnly(req,resp);
		}
	}
	
	/**
	 * 检查版块名字是否重名
	 * description:
	 * 2015年10月22日 下午5:19:28
	 * casper
	 * void
	 * @param req
	 * @param resp
	 */
	private void checkBoardNameOnly(HttpServletRequest req,
			HttpServletResponse resp) {
		String boardName = req.getParameter("boardName");
		boolean isOnly = boardService.checkBoardNameOnly(boardName);
		if(isOnly){
			out.write("true");
		}else{
			out.write("false");
		}
	}

	/**
	 * 跳转管理员主页
	 * description:
	 * 2015年10月22日 下午4:43:16
	 * casper
	 * void
	 * @param req
	 * @param resp
	 * @throws IOException 
	 */
	private void adminIndex(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		ArrayList<Board> boards = boardService.selectAllBoards();
		if(boards!=null){
			ArrayList<Board> pboards = new ArrayList<Board>();
			for(Board b:boards){
				if(b.getPbid() == 0){
					pboards.add(b);
				}
			}
			session.setAttribute("boards", boards);
			session.setAttribute("pboards", pboards);
			resp.sendRedirect("admin-index.jsp");
		}
		
	}

	/**
	 * 添加
	 * description:
	 * 2015年10月22日 下午4:19:51
	 * casper
	 * void
	 * @param req
	 * @param resp
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void addBoard(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String pbid = req.getParameter("pbid");
		String boardName = req.getParameter("boardname");
		String boardDesc = req.getParameter("boarddesc");
		Board newBoard = new Board(boardName, boardDesc, Integer.parseInt(pbid), DateUtil.toDateStr(new Date()));
		if(boardService.addBoard(newBoard) == 1){
			req.getRequestDispatcher("BoardServlet?op=adminIndex").forward(req, resp);
		}{
			
		}
		
	}
       
	

}
